/**
 * 登录路由
 *
 * 主要功能：
 * - 用户登录
 *
 * @file login.js
 * @version 1.0.0
 * @author "nailuo"
 * @created 2025-8-30
 * @lastModified 2025-8-30
 */

const { user } = require("../../database/index.js");
const { jwtUtils,emailUtils } = require("../../utils/index.js");

// 发送验证码
const sendVerificationCode = async (req, res) => {
    try {
        req.session.userData = await user.loginUser(req.body.username, req.body.password);
        req.session.verificationCode = emailUtils.sendEmail(req.session.userData.email);
        res.status(200).json({
            request: {
                method: req.method,
                path: req.path,
                headers: req.headers,
                body: req.body,
                path: req.path
            },
            success: true,
            message: "验证码已发送",
            code: 200,
        });
        setTimeout(() => {
            req.session.verificationCode = "";
            req.session.save();
        }, 60000); // 1分钟后失效
    } catch (error) {
        res.status(401);
        res.set('Content-Type', 'text/json');
        res.send({
            request: {
                method: req.method,
                path: req.path,
                headers: req.headers,
                body: req.body,
                path: req.path
            },
            success: false,
            message: "验证码发送失败" + error.message,
            code: 401,
        });
    }
};

// 验证验证码，并登录
const verifyCode = (req, res) => {
    //判断验证码是否过期
    if (!req.session.verificationCode) {
        res.status(401);
        res.set('Content-Type', 'text/json');
        res.send({
            request: {
                method: req.method,
                path: req.path,
                headers: req.headers,
                body: req.body,
                path: req.path
            },
            success: false,
            message: "验证码已过期",
            code: 401
        });
        return;
    }
    //判断验证码是否正确
    if (req.query.code === req.session.verificationCode) {
        res.status(200);
        res.set('Content-Type', 'text/json');
        res.send({
            request: {
                method: req.method,
                path: req.path,
                headers: req.headers,
                body: req.body,
                path: req.path
            },
            success: true,
            message: "登录成功",
            code: 200,
            data: {
                token: jwtUtils.generateToken(req.session.userData)
            }
        });
    } else {
        res.status(401);
        res.set('Content-Type', 'text/json');
        res.send({
            request: {
                method: req.method,
                path: req.path,
                headers: req.headers,
                body: req.body,
                path: req.path
            },
            success: false,
            message: "验证码错误",
            code: 401,
        });
    }
};

module.exports = {
    sendVerificationCode,
    verifyCode
}

